package com.ruoyi.basebill.task;

import com.ruoyi.basebill.domain.*;
import com.ruoyi.basebill.mapper.OmsSalereturnbillMapper;
import com.ruoyi.basebill.service.*;
import com.ruoyi.basebill.service.exception.DataNullException;
import com.ruoyi.basebill.service.impl.PushSaleReturnServiceImpl;
import com.ruoyi.basebill.task.util.OmsTaskUtil;
import com.ruoyi.basebill.util.OmsUtil;
import com.ruoyi.basedata.domain.BdCustomer;
import com.ruoyi.basedata.domain.BdWarehouse;
import com.ruoyi.basedata.domain.OmsOrgunit;

import com.ruoyi.basedata.service.IOmsOrgunitService;

import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @projectName: wfz
 * @package: com.ruoyi.basebill.task
 * @className: pushSaleIssueTask
 * @author: Eric
 * @description: TODO
 * @date: 2023/2/20 15:53
 * @version: 1.0
 */

@Component("pushSaleIssue")
public class PushSaleIssueTask {

    @Autowired
    private IOmsSalereturnbillService salereturnbillService;
    @Autowired
    private IPushSaleReturnService pushSaleReturnService;
    @Autowired
    private OmsUtil omsUtil;
    @Autowired
    private IOmsOrgunitService omsOrgunitService;

    //销售出库
    @Autowired
    private IOmsSaleissuebillService omsSaleissuebillService;
    //采购入库
    @Autowired
    private IOmsPurinwarehsbillService omsPurinwarehsbillService;

    //调拨
    @Autowired
    private IOmsStocktransferbillService omsStocktransferbillService;

    //其他出库单
    @Autowired
    private IOmsOtherissuebillService omsOtherissuebillService;

    @Autowired
    private PushSaleIssueTask pushSaleIssueTask;

    @Autowired
    private OmsSalereturnbillMapper omsSalereturnbillMapper;
    @Autowired
    private OmsTaskUtil omsTaskUtil;

    private final static Logger logger = LoggerFactory.getLogger(PushSaleIssueTask.class);


    /**
     * 下推自动任务
     */
    public void pushSaleIssueTask() {
//        OmsSalereturnbill omsSalereturnbill = new OmsSalereturnbill();
//        omsSalereturnbill.setIscreatebill(0l);
//        List<OmsSalereturnbill> omsSalereturnbills = salereturnbillService.selectOmsSalereturnbillList(omsSalereturnbill);

        List<OmsSalereturnbill> omsSalereturnbills = omsSalereturnbillMapper.getSalereturnbill(); //查找isCreateBill

        for (OmsSalereturnbill salereturnbill : omsSalereturnbills) {
            StringBuffer reason = new StringBuffer();
            reason.append("Over");
            Long id = salereturnbill.getId();
            //通过Id 还原整个销售退货的对象
            OmsSalereturnbill omsSalereturnbill1 = salereturnbillService.selectOmsSalereturnbillById(id);

            //校验是否为空
            StringBuffer stringBuffer = omsUtil.checkIsNull(omsSalereturnbill1);
            if (!"Over".equals(stringBuffer.toString())) {
                omsSalereturnbill1.setIscreatebill(0l);
                omsSalereturnbill1.setReason(stringBuffer.toString());
                salereturnbillService.updateOmsSalereturnbill(omsSalereturnbill1);
                continue;
            }
            try {
                pushSaleIssueTask.pushSaleIssue(omsSalereturnbill1);
                omsSalereturnbill1.setIscreatebill(1l);
                omsSalereturnbill1.setReason("下发成功");
                salereturnbillService.updateOmsSalereturnbill(omsSalereturnbill1);
            } catch (DataNullException e) {
                //先回滚数据（）
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                //接到异常将异常信息，set到单据失败原因中去
                omsSalereturnbill1.setIscreatebill(-1l);
                omsSalereturnbill1.setReason(e.getMessage());
                salereturnbillService.updateOmsSalereturnbill(omsSalereturnbill1);
            }
        }

    }

    /**
     * 下推自动任务
     */
    public void pushSaleIssueTaskZC() {
//        OmsSalereturnbill omsSalereturnbill = new OmsSalereturnbill();
//        omsSalereturnbill.setIscreatebill(0l);
//        List<OmsSalereturnbill> omsSalereturnbills = salereturnbillService.selectOmsSalereturnbillList(omsSalereturnbill);

        List<OmsSalereturnbill> omsSalereturnbills = omsSalereturnbillMapper.getSalereturnbillZC(); //查找isCreateBill
        if (StringUtils.isEmpty(omsSalereturnbills)){
            return;
        }
        for (OmsSalereturnbill salereturnbill : omsSalereturnbills) {
            StringBuffer reason = new StringBuffer();
            reason.append("Over");
            Long id = salereturnbill.getId();
            //通过Id 还原整个销售退货的对象
            OmsSalereturnbill omsSalereturnbill1 = salereturnbillService.selectOmsSalereturnbillById(id);

            //校验是否为空
            StringBuffer stringBuffer = omsUtil.checkIsNull(omsSalereturnbill1);
            if (!"Over".equals(stringBuffer.toString())) {
                omsSalereturnbill1.setIscreatebill(0l);
                omsSalereturnbill1.setReason(stringBuffer.toString());
                salereturnbillService.updateOmsSalereturnbill(omsSalereturnbill1);
                continue;
            }
            try {
                pushSaleIssueTask.pushSaleIssue(omsSalereturnbill1);
                omsSalereturnbill1.setIscreatebill(1l);
                omsSalereturnbill1.setReason("下发成功");
                salereturnbillService.updateOmsSalereturnbill(omsSalereturnbill1);
            } catch (DataNullException e) {
                //先回滚数据（）
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                //接到异常将异常信息，set到单据失败原因中去
                omsSalereturnbill1.setIscreatebill(-1l);
                omsSalereturnbill1.setReason(e.getMessage());
                salereturnbillService.updateOmsSalereturnbill(omsSalereturnbill1);
            }
        }

    }

    @Transactional(rollbackFor=Exception.class)
    public void pushSaleIssue(OmsSalereturnbill omsSalereturnbill1) throws DataNullException {
        StringBuffer reason = new StringBuffer(); //失败原因
        reason.append("Over");
//        omsSalereturnbill1.setRemark("dev");
//        salereturnbillService.updateOmsSalereturnbill(omsSalereturnbill1);
//        if(true){
//            throw new DataNullException("测试是否回滚");
//        }
        //如果整张单据的数量均为品控拒绝处理数量+仓库拒绝处理数量=售后数量，则直接标记为1 ，无需处理
        OmsSalereturnbill resalereturnbill = pushSaleReturnService.rebuildSalereturn(omsSalereturnbill1);
        if (resalereturnbill.getOmsSalereturnbillentryList().size() == 0) {
            omsSalereturnbill1.setIscreatebill(1l);
            salereturnbillService.updateOmsSalereturnbill(omsSalereturnbill1);
            return ;
        }
        String customercode = resalereturnbill.getCustomercode();
        BdCustomer customer = omsUtil.getCustomer(customercode);
        Long isinternal = customer.getIsinternal();
        Long iscostcenter = customer.getIscostcenter();
        Boolean isInternal = true; //是否内部客户；
        if (isinternal == 0l && iscostcenter == 0l) {
            //若是外部客户生成内则先生成一张外部客户退货的销售出库（红字）
//            OmsSaleissuebill omsSaleissuebill = pushSaleReturnService.pushSaleIssueForOut(resalereturnbill, reason, resalereturnbill.getInvoicename());
//            omsSaleissuebillService.insertOmsSaleissuebill(omsSaleissuebill);


              isInternal = false;
        }
        String invoicecode = resalereturnbill.getInvoicecode();
        OmsOrgunit omsOrgunit = omsUtil.getOmsOrgunit(invoicecode);
        //根据invoiceCode取结算组织，判断结算组织的级次，如果是一级，则生成一张库存调拨单，否则跳过此步骤
        Long level = omsOrgunit.getLevel();
        if (level == 1l&&isInternal) { //计算组织是1级，且是内部客户的情况下
            OmsStocktransferbill omsStocktransferbill = pushSaleReturnService.pushStockTransferForFir(resalereturnbill, reason);
            omsStocktransferbillService.insertOmsStocktransferbill(omsStocktransferbill);
        }
        if(level != 1l) { //结算组织不为1级的情况下
            //否则逐级生成本级级组织的采购入库单（红字）和上级组织的销售出库单（红字）
            //通过级次去判断

            for (int i = level.intValue(); i > 1; i--) {
                //先生成本级的采购入库红
//                Long parentid = omsOrgunit.getParentid();
//                OmsOrgunit parenOrgunit1 = omsOrgunitService.selectOmsOrgunitById(parentid);
                OmsOrgunit omsOrgunit1 = omsUtil.getOmsOrgunit(invoicecode);
                String orgnumber = omsOrgunit1.getParentorgnumber(); //上级组织编码
                //本级组织存在的话，上级组织必定存在
                if (i == level) {
                    OmsPurinwarehsbill omsPurinwarehsbill = pushSaleReturnService.pushPurInWarehseForlow(resalereturnbill, reason, invoicecode, orgnumber, true);
                    omsPurinwarehsbillService.insertOmsPurinwarehsbill(omsPurinwarehsbill);
                } else {
                    OmsPurinwarehsbill omsPurinwarehsbill = pushSaleReturnService.pushPurInWarehseForlow(resalereturnbill, reason, invoicecode, orgnumber, false);
                    omsPurinwarehsbillService.insertOmsPurinwarehsbill(omsPurinwarehsbill);
                }
                //生成上级组织的销售出库红字字
                OmsSaleissuebill omsSaleissuebill = pushSaleReturnService.pushSaleIssueForSup(resalereturnbill, reason, invoicecode, orgnumber);
                omsSaleissuebillService.insertOmsSaleissuebill(omsSaleissuebill);
                invoicecode = orgnumber;
            }
        }

        //结算组织的一级组织
        String firstorgnumber = omsOrgunit.getFirstorgnumber();

        String returnwarehousecode = resalereturnbill.getOmsSalereturnbillentryList().get(0).getReturnwarehousecode();
        BdWarehouse bdWarehouse = omsUtil.getBdWarehouse(returnwarehousecode);
        String storageorgnumber = bdWarehouse.getStorageorgnumber(); //发货组织，明细仓库所在的库存组织
        OmsOrgunit tuhuozz = omsUtil.getOmsOrgunit(storageorgnumber);
        if (!firstorgnumber.equals(storageorgnumber)) {
            //判断是否分子公司
            Long js = omsOrgunit.getIssub();
            Long th = tuhuozz.getIssub();

            if(js!=null&th!=null&&js==1l&&th==1l){
                //生成js到实业的退货,正常的处理逻辑
                OmsSaleissuebill omsSaleissuebill = pushSaleReturnService.pushSaleIssueForSup(resalereturnbill, reason, firstorgnumber, "1.10.100");
                omsSaleissuebillService.insertOmsSaleissuebill(omsSaleissuebill);

                OmsPurinwarehsbill omsPurinwarehsbill = pushSaleReturnService.pushPurInWarehseForlow(resalereturnbill, reason, firstorgnumber, "1.10.100", false);
                omsPurinwarehsbillService.insertOmsPurinwarehsbill(omsPurinwarehsbill);

                //实业到th的交易
                OmsSaleissuebill omsSaleissuebilltoth = pushSaleReturnService.pushSaleIssueForFir(resalereturnbill, reason, "1.10.100", storageorgnumber);
                omsSaleissuebillService.insertOmsSaleissuebill(omsSaleissuebilltoth);
                OmsPurinwarehsbill omsPurinwarehsbilltoth = pushSaleReturnService.pushPurInWarehseForFirst(resalereturnbill, reason,storageorgnumber,"1.10.100");
                omsPurinwarehsbillService.insertOmsPurinwarehsbill(omsPurinwarehsbilltoth);
            }else{
                //如果不等，则生成发货组织的销售出库单（红字）和一级组织的采购入库单（红字）；如果相等则跳过此步骤
                OmsSaleissuebill omsSaleissuebill = pushSaleReturnService.pushSaleIssueForFir(resalereturnbill, reason, firstorgnumber, storageorgnumber);
                omsSaleissuebillService.insertOmsSaleissuebill(omsSaleissuebill);
                OmsPurinwarehsbill omsPurinwarehsbill = pushSaleReturnService.pushPurInWarehseForFirst(resalereturnbill, reason,storageorgnumber,firstorgnumber);
                omsPurinwarehsbillService.insertOmsPurinwarehsbill(omsPurinwarehsbill);
            }


        }
        OmsSalereturnbill omsSalereturnbill2 = omsUtil.rebuildSalereturn(resalereturnbill, "1");//品控承担数量大于0
        if (omsSalereturnbill2.getOmsSalereturnbillentryList().size() > 0) {
            OmsOtherissuebill omsOtherissuebill = pushSaleReturnService.pushOtherIssue(omsSalereturnbill2, reason);
            omsOtherissuebillService.insertOmsOtherissuebill(omsOtherissuebill);
        }
        OmsSalereturnbill omsSalereturnbill3 = omsUtil.rebuildSalereturn(resalereturnbill, "2");
        if (omsSalereturnbill3.getOmsSalereturnbillentryList().size() > 0) {
            OmsStocktransferbill omsStocktransferbill = pushSaleReturnService.pushStockTransferForQty(omsSalereturnbill3, reason);
            omsStocktransferbillService.insertOmsStocktransferbill(omsStocktransferbill);
        }
    }

    /**
     * 外部销售退货单生成事务
     */
    public void pushSaleIssueForOut(){
        //处理重复单据
        omsTaskUtil.dealRepeatSalereturnbill();
        List<OmsSalereturnbill> omsSalereturnbills = omsSalereturnbillMapper.getOmsSalereturnbill(); //查找isoutCreateBill

        for (OmsSalereturnbill salereturnbill : omsSalereturnbills) {
            StringBuffer reason = new StringBuffer();

            reason.append("Over");
            Long id = salereturnbill.getId();
            //通过Id 还原整个销售退货的对象
            //校验是否为空
            OmsSalereturnbill omsSalereturnbill = salereturnbillService.selectOmsSalereturnbillById(id); //校验原单的相应信息
            StringBuffer stringBuffer = omsUtil.checkIsNull(omsSalereturnbill);
            if (!"Over".equals(stringBuffer.toString())) {
                omsSalereturnbill.setIscreateoutbill(-1l);
                omsSalereturnbill.setOutreason(stringBuffer.toString());
                salereturnbillService.updateOmsSalereturnbillHead(omsSalereturnbill);
                continue;
            }

            //通过Id 还原整个销售退货的对象
            OmsSalereturnbill omsSalereturnbill1 = salereturnbillService.selectOmsSalereturnbillSummaryEntryById(id);
            if(omsSalereturnbill1==null){ //说明为无需下发
                omsSalereturnbill.setIscreateoutbill(1l);
                omsSalereturnbill.setOutreason("下发成功");
                salereturnbillService.updateOmsSalereturnbillHead(omsSalereturnbill1);
                continue;
            }
            try {

                int i = pushSaleIssueTask.pushOutSaleIssue(omsSalereturnbill1);
                if(i==1){
                    omsSalereturnbill1.setIscreateoutbill(1l);
                    omsSalereturnbill1.setOutreason("下发成功");
                    salereturnbillService.updateOmsSalereturnbillHead(omsSalereturnbill1);
                }else{
                    omsSalereturnbill1.setIscreateoutbill(-2l);
                    salereturnbillService.updateOmsSalereturnbillHead(omsSalereturnbill1);
                }

            } catch (DataNullException e) {
                //先回滚数据（）
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                //接到异常将异常信息，set到单据失败原因中去
                omsSalereturnbill1.setIscreateoutbill(-1l);
                omsSalereturnbill1.setOutreason(e.getMessage());
                salereturnbillService.updateOmsSalereturnbillHead(omsSalereturnbill1);
            }
        }
    }

    @Transactional(rollbackFor=Exception.class)
    public int pushOutSaleIssue(OmsSalereturnbill omsSalereturnbill1) throws DataNullException {
        StringBuffer reason = new StringBuffer(); //失败原因

        //如果整张单据的数量均为品控拒绝处理数量+仓库拒绝处理数量=售后数量，则直接标记为1 ，无需处理
        OmsSalereturnbill resalereturnbill = pushSaleReturnService.rebuildSalereturn(omsSalereturnbill1);
        logger.info("销售外部退货重组完："+resalereturnbill.toString());

        if (resalereturnbill.getOmsSalereturnbillentryList().size() == 0) {
            omsSalereturnbill1.setIscreatebill(1l);
            salereturnbillService.updateOmsSalereturnbill(omsSalereturnbill1);
            return 1;
        }
        String customercode = resalereturnbill.getCustomercode();
        BdCustomer customer = omsUtil.getCustomer(customercode);
        Long isinternal = customer.getIsinternal();
        Long iscostcenter = customer.getIscostcenter();
        Boolean isInternal = true; //是否内部客户；
        if (isinternal == 0l && iscostcenter == 0l) {
            //若是外部客户生成内则先生成一张外部客户退货的销售出库（红字）
            OmsSaleissuebill omsSaleissuebill = pushSaleReturnService.pushSaleIssueForOut(resalereturnbill, reason, resalereturnbill.getInvoicename());
            omsSaleissuebillService.insertOmsSaleissuebill(omsSaleissuebill);
            return 1;
        }else{
            //若是内部客户
            return 0 ;
        }
    }

}
